package com.example.academic_affairs_system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.academic_affairs_system.common.RPage;
import com.example.academic_affairs_system.exception.SystemException;
import com.example.academic_affairs_system.mapper.AasStudentCoursesMapper;
import com.example.academic_affairs_system.model.dto.studentCourses.StudentCoursesDTO;
import com.example.academic_affairs_system.model.dto.studentCourses.StudentCoursesPageDTO;
import com.example.academic_affairs_system.model.entity.AasStudentCourses;
import com.example.academic_affairs_system.model.vo.LoginResponseVO;
import com.example.academic_affairs_system.model.vo.studentCourses.StudentCoursesVO;
import com.example.academic_affairs_system.service.IAasStudentCoursesService;
import com.example.academic_affairs_system.utils.TokenUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 学生和课表的关联数据，用于登记学生的课程成绩 服务实现类
 *
 * @author hjx
 * @since 2023-01-31
 */
@Service
public class AasStudentCoursesServiceImpl
    extends ServiceImpl<AasStudentCoursesMapper, AasStudentCourses>
    implements IAasStudentCoursesService {
  @Resource private SqlSessionFactory sqlSessionFactory;
  @Resource private HttpServletRequest request;

  @Override
  public int batchRelated(Collection<Long> studentIds, Collection<Long> coursesIds) {
    List<AasStudentCourses> list = new ArrayList<>();
    for (Long coursesId : coursesIds) {
      for (Long studentId : studentIds) {
        list.add(AasStudentCourses.builder().coursesId(coursesId).studentId(studentId).build());
      }
    }
    if (CollectionUtil.isNotEmpty(list)) {
      // 利用 sqlsession 实现批处理
      SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
      AasStudentCoursesMapper mapper = sqlSession.getMapper(AasStudentCoursesMapper.class);
      int i = 0;
      for (; i < list.size(); i++) {
        mapper.insert(list.get(i));
        if (i % 2000 == 0) {
          sqlSession.commit();
          sqlSession.clearCache();
        }
      }
      sqlSession.commit();
      sqlSession.clearCache();
      return i;
    }
    return 0;
  }

  @Override
  public RPage<StudentCoursesVO> getClassStudentCourses(StudentCoursesPageDTO dto) {
    return RPage.<StudentCoursesVO>createDto(dto)
        .execute(
            (page) -> baseMapper.getClassStudentCourses(page, dto.getCoursesId(), dto.getClassId()))
        .build();
  }

  @Override
  public RPage<StudentCoursesVO> getStudentCourses(StudentCoursesPageDTO dto) {
    long userId;
    if (dto.getStudentId() == null) {
      LoginResponseVO loginResponseVO = TokenUtils.parseToken(request);
      userId = loginResponseVO.getUserId();
    } else {
      userId = dto.getStudentId();
    }
    return RPage.<StudentCoursesVO>createDto(dto)
        .execute((page) -> baseMapper.getStudentCourses(page, userId))
        .build();
  }

  @Override
  public int editStudentGrades(StudentCoursesDTO dto) {
    AasStudentCourses aasStudentCourses =
        baseMapper.selectOne(
            Wrappers.<AasStudentCourses>lambdaQuery()
                .eq(AasStudentCourses::getCoursesId, dto.getCoursesId())
                .eq(AasStudentCourses::getStudentId, dto.getStudentId()));
    if (aasStudentCourses == null) {
      throw new SystemException(-999, "学生没有选修该课程", null);
    }
    aasStudentCourses.setGrades(dto.getGrades());
    return baseMapper.updateById(aasStudentCourses);
  }
}
